# -*- coding: utf-8 -*-


import flask
import sqlalchemy.exc

from patentwars import app
from patentwars import models
from patentwars import forms
from patentwars import db


@app.route('/login', methods=('GET', 'POST'))
def login():
    error = None
    if flask.request.method == 'POST':
        if flask.request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif flask.request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            flask.session['logged_in'] = True
            flask.flash('You were logged in')
            return flask.redirect(flask.url_for('index'))
    return flask.render_template('login.html', error=error)

@app.route('/logout')
def logout():
    flask.session.pop('logged_in', None)
    flask.flash('You were logged out')
    return flask.redirect(flask.url_for('index'))

@app.route('/')
def index():
    return flask.render_template('layout.html')

@app.route('/product/')
def all_products():
    products = models.Product.query.all()
    return flask.render_template('all_products.html', products=products)

@app.route('/product/<product_id>')
def show_product(product_id):
    product = models.Product.query.get_or_404(product_id)
    return flask.render_template('show_product.html', product=product)

@app.route('/product/make', methods=('GET', 'POST'))
def make_product():
    form = forms.ProductForm()
    form.technologies.choices = [(t.id, t.name) for
                                 t in models.Technology.query.all()]
    if form.validate_on_submit():
        product = models.Product(name=form.name.data)
        try:
            db.session.add(product)
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            flask.flash(u"This product already exists.")
            return flask.render_template('make_product.html', form=form)
        for technology_id in form.technologies.data:
            application = models.Application(product=product,
                    technology=models.Technology.query.get(technology_id))
            db.session.add(application)
        db.session.commit()
        flask.flash(u"New product created.")
        return flask.redirect(flask.url_for('show_product',
                                            product_id=product.id))
    else:
        return flask.render_template('make_product.html', form=form)


@app.route('/technology/<technology_id>')
def show_technology(technology_id):
    technology = models.Technology.query.get_or_404(technology_id)
    return flask.render_template('show_technology.html', technology=technology)

@app.route('/technology/make', methods=('GET', 'POST'))
def make_technology():
    form = forms.TechnologyForm()
    if form.validate_on_submit():
        flask.flash(u"New technology created.")
        technology = models.Technology(name=form.name.data)
        try:
            db.session.add(technology)
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            flask.flash(u"This technology already exists.")
            return flask.render_template('make_technology.html', form=form)
        return flask.redirect(flask.url_for('show_technology',
                                            technology_id=technology.id))
    else:
        return flask.render_template('make_technology.html', form=form)
